package utils;

import cn.hutool.json.JSONObject;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class FormatData {

    private String dataUser = "";
    private String dataType = "";
    private String dataName = "";
    private String dataCrypt = "";
    private String dataTime = "";
    private String dataHash = "";
    private int dataLevel = 0;

    private JSONObject dataIndex = new JSONObject();
    private JSONObject head = new JSONObject();
    private JSONObject body = new JSONObject();
    private JSONObject signature = new JSONObject();
    private JSONObject formatData = new JSONObject();

    public void setDataUser(String dataUser) {
        this.dataUser = dataUser;
    }

    public void setDataType(String dataType) {
        this.dataType = dataType;
    }

    public void setDataName(String dataName) {
        this.dataName = dataName;
    }

    public void setDataLevel(int dataLevel) {
        this.dataLevel = dataLevel;
    }

    public void setDataCrypt(String dataCrypt) {
        this.dataCrypt = dataCrypt;
    }

    public void putDataIndex(String key, String value) {
        dataIndex.put(key, value);
    }

    public void putBody(String key, String value) {
        body.put(key, value);
    }

    public void putSignature(String key, String value) {
        signature.put(key, value);
    }

    public void clean() {
        head.clear();
        body.clear();
        signature.clear();
        formatData.clear();
    }

    public static String GetMd5(String str) {
        byte[] md5 = DigestUtils.md5(str.getBytes());
        return Hex.encodeHexString(md5);
    }

    public String getKeys() {
        dataHash = GetMd5(body.toString());
        return dataUser + "_" + dataHash;
    }

    public JSONObject toJSON() {

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置时区为东八区
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

        head.set("dataUser", dataUser);
        head.set("dataType", dataType);
        head.set("dataName", dataName);
        head.set("dataLevel", dataLevel);
        head.set("dataHash", dataHash);
        head.set("dataTime", dateFormat.format(now));
        head.set("dataIndex", dataIndex);

        formatData.set("head", head);
        formatData.set("body", body);
        formatData.set("signature", signature);

        return formatData;
    }
}
